package org.example.test1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DistributeClient {
    private String connectString = "47.108.48.236:2182";
    private int sessionTimeout = 300000;
    private ZooKeeper zooKeeper;
    private String path = "/server";
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DistributeClient client = new DistributeClient();
        // 1. 连接 zookeeper, 监听 /servers 下子节点变化
        client.getConnection();
        // 2. 处理业务逻辑
        client.business();
    }

    private void business() throws InterruptedException {
        Thread.sleep(Integer.MAX_VALUE);
    }

    private void getServerList() throws InterruptedException, KeeperException {
        List<String> childrens = zooKeeper.getChildren(path, true);
        List<String> list = new ArrayList<>();
        for (String children : childrens) {
            byte[] data = zooKeeper.getData(path +  "/" + children, false, null);
            list.add("node: " + children + " val: " + new String(data));
        }
        System.out.println("list: " + list);
    }

    private void getConnection() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("event: " + watchedEvent);
                try {
                    getServerList();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (KeeperException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
